#!/bin/bash

set -xe

# Prepare the environment
export SYSTEM=android
export ARCH=arm
export ANDROID_SYSROOT=@ANDROID_SYSROOT@
export ARCH=@ANDROID_ARCH_NAME@
export ABI=@ANDROID_ABI@
if [[ $ABI = "armeabi" ]]; then
    export MACHINE=arm
elif [[ $ABI = "armeabi-v7a" ]]; then
    export MACHINE=armv7
else
    export MACHINE=$ARCH
fi
export SYSTEM=android
export ANDROID_API=android
export SYSROOT=${ANDROID_SYSROOT}
export NDK_SYSROOT=${ANDROID_SYSROOT}
export ANDROID_NDK_SYSROOT=${ANDROID_SYSROOT}
export ANDROID_DEV=${ANDROID_SYSROOT}/usr
export HOSTCC=gcc
export PATH=$(dirname @CMAKE_C_COMPILER@):${PATH}
export CC=@CMAKE_C_COMPILER@

# Only build what we need
./config no-idea               \
         no-camellia           \
         no-seed               \
         no-bf                 \
         no-cast               \
         no-des                \
         no-rc2                \
         no-rc4                \
         no-rc5                \
         no-md2                \
         no-md4                \
         no-ripemd             \
         no-mdc2               \
         no-rsax               \
         no-dsa                \
         no-dh                 \
         no-ec                 \
         no-ecdsa              \
         no-ecdh               \
         no-sock               \
         no-ssl2               \
         no-ssl3               \
         no-err                \
         no-krb5               \
         no-engine             \
         no-srtp               \
         no-speed              \
         no-unit-test          \
         -DOPENSSL_NO_SHA512   \
         -DOPENSSL_NO_SHA0     \
         -w                    \
         -fPIC                 \
     --openssldir=@PROJECT_BINARY_DIR@/@ABI@

# Patch the Makefile in order to:
#   1) change optimization from -O3 to -Os
#   2) remove the -mandroid flag (it messes with make depend)
#   3) allow to add DEPFLAG values from the command line
#   4) use the proper ar command
#   5) use the proper ranlib command
sed -i.backup \
    -e "s/-O3/-Os/g" \
    -e "s/\-mandroid//g" \
    -e "s/DEPFLAG=/DEPFLAG+=/g" \
    -e "s#^AR=.*#AR= @CMAKE_AR@ $(ARFLAGS) r#" \
    -e "s#^RANLIB=.*#RANLIB= @CMAKE_RANLIB@#" \
    Makefile

# Patch a file removing a function that brings in many unneeded dependencies
sed -i.backup /OPENSSL_cleanse/d crypto/sha/sha256.c

make depend DEPFLAG=-I@ANDROID_TOOLCHAIN_ROOT@/lib/gcc/@ANDROID_TOOLCHAIN_MACHINE_NAME@/4.9/include
make build_crypto
make build_ssl

mkdir -p @PROJECT_BINARY_DIR@/openssl/lib
mkdir -p @PROJECT_BINARY_DIR@/openssl/include
cp -RL include/* @PROJECT_BINARY_DIR@/openssl/include
cp libcrypto.a @PROJECT_BINARY_DIR@/openssl/lib
cp libssl.a @PROJECT_BINARY_DIR@/openssl/lib